<?php


namespace app\mobile\controller;

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');

use app\common\model\User;
use app\common\Tools;
use think\Controller;
use think\Db;
use think\facade\Request;


class Index extends Controller
{

    /**
     * APP檢查更新
     */
    public function mb_CheckUpdate()
    {
        $ID = Request::has('ID') ? intval(Request::param('ID')) : 0;
        if (!$ID) mb_OutMessage(ErrCode_Toast, '参数有误');

        $Data = Db::table('app_config')->field('Version,Updates,DownloadPage,TimeUpdated')->where("ID='$ID'")->find();
        mb_OutMessage(ErrCode_Normal, '', $Data);
    }

    public function mb_LogResult()
    {
        $Logs = Request::has('Logs') ? Request::param('Logs') : '';
        Tools::mb_LogResult($Logs);
        echo 'success';
    }

    /**
     * 登录
     */
    public function mb_Login()
    {

        $Name = Request::has('Name') ? addslashes(Request::param('Name')) : '';
        $Pass = Request::has('Pass') ? addslashes(Request::param('Pass')) : '';
        $EncPass = md5($Pass);

        $User = new User();
        $UserData = $User->mb_Get("Name='$Name' AND EncPass='$EncPass' AND IsDeleted='0'");
        if ($UserData == null) {
            mb_OutMessage(ErrCode_Toast, '账号或密码有误！');
        }
        if ($UserData['Level'] != Level_CRMUser) {
            mb_OutMessage(ErrCode_Toast, '账号或密码有误！');
        }
        $CompanyID = $UserData['CompanyID'];
        $CompanyData = Db::table('company')->field('ID,Name')->where("ID='$CompanyID'")->find();

        Db::startTrans();
        try {
            $Token = md5($UserData->Name . time());
            $UserData->MobileToken = $Token;
            $UserData->save();
            Db::commit();
            $Data = array(
                'Name' => $UserData->Name,
                'Nick' => $UserData->Nick,
                'Regist' => $UserData->Regist,
                'Login' => $UserData->Login,
                'Token' => $Token,
                'WeChat' => $UserData->WeChat,
                'QQ' => $UserData->QQ,
                'Phone' => $UserData->Phone,
                'Email' => $UserData->Email,
                'Sex' => $UserData->Sex,
                'Remark' => $UserData->Remark,
                'SuperiorID' => $UserData->SuperiorID,
                'Icon' => $UserData->Icon
            );
            if ($CompanyData == null) {
                $Data['CompanyName'] = '';
            } else {
                $Data['CompanyName'] = $CompanyData['Name'];
            }
            mb_OutMessage(ErrCode_Normal, '登入成功', $Data);
        } catch (\Exception $e) {
            Db::rollback();
            mb_OutMessage(ErrCode_Toast, $e->getMessage());
        }
    }

    public function mb_TokenLogin()
    {
        $Token = Request::has('Token') ? Request::param('Token') : '';
        if (!$Token) mb_OutMessage(ErrCode_Distance, ErrMsg_Distance);

        $User = new User();
        $UserData = $User->mb_Get("MobileToken='$Token' AND IsDeleted='0'");
        if ($UserData == null) {
            mb_OutMessage(ErrCode_Distance, ErrMsg_Distance);
        }
        if ($UserData['Level'] != Level_CRMUser) {
            mb_OutMessage(ErrCode_Distance, ErrMsg_Distance);
        }
        $CompanyID = $UserData['CompanyID'];
        $CompanyData = Db::table('company')->field('ID,Name')->where("ID='$CompanyID'")->find();
        $Data = array(
            'Name' => $UserData->Name,
            'Nick' => $UserData->Nick,
            'Regist' => $UserData->Regist,
            'Login' => $UserData->Login,
            'Token' => $Token,
            'WeChat' => $UserData->WeChat,
            'QQ' => $UserData->QQ,
            'Phone' => $UserData->Phone,
            'Email' => $UserData->Email,
            'Sex' => $UserData->Sex,
            'Remark' => $UserData->Remark,
            'SuperiorID' => $UserData->SuperiorID,
            'Icon' => $UserData->Icon
        );
        if ($CompanyData == null) {
            $Data['CompanyName'] = '';
        } else {
            $Data['CompanyName'] = $CompanyData['Name'];
        }
        mb_OutMessage(ErrCode_Normal, '登入成功', $Data);
    }

    /**
     * 登出
     */
    public function mb_Logout()
    {
        $Token = Request::has('Token') ? addslashes(Request::param('Token')) : '';

        $User = new User();
        $UserData = $User->mb_Get("MobileToken='$Token' AND IsDeleted='0'");
        if ($UserData == null || $UserData['Level'] != Level_CRMUser) {
            mb_OutMessage(ErrCode_Normal, '登出成功');
        } else {
            Db::startTrans();
            try {
                $UserData->MobileToken = '';
                $UserData->save();
                Db::commit();
                mb_OutMessage(ErrCode_Normal, '登出成功');
            } catch (\Exception $e) {
                Db::rollback();
                mb_OutMessage(ErrCode_Normal, '登出成功');
            }
        }
    }

    /**
     * 保存個人信息
     */
    public function mb_Save()
    {
        $Token = Request::has('Token') ? addslashes(Request::param('Token')) : '';

        $Nick = Request::has('Nick') ? addslashes(Request::param('Nick')) : '';
        $Sex = Request::has('Sex') ? intval(Request::param('Sex')) : 0;
        $WeChat = Request::has('WeChat') ? addslashes(Request::param('WeChat')) : '';
        $QQ = Request::has('QQ') ? addslashes(Request::param('QQ')) : '';
        $Phone = Request::has('Phone') ? addslashes(Request::param('Phone')) : '';
        $Email = Request::has('Email') ? addslashes(Request::param('Email')) : '';
        $Remark = Request::has('Remark') ? addslashes(Request::param('Remark')) : '';

        $User = new User();
        $UserData = $User->mb_Get("MobileToken='$Token' AND IsDeleted='0'");
        if ($UserData == null || $UserData['Level'] != Level_CRMUser) mb_OutMessage(ErrCode_Distance, ErrMsg_Distance);

        Db::startTrans();
        try {
            $UserData->Nick = $Nick;
            $UserData->Sex = $Sex;
            $UserData->WeChat = $WeChat;
            $UserData->QQ = $QQ;
            $UserData->Phone = $Phone;
            $UserData->Email = $Email;
            $UserData->Remark = $Remark;
            $UserData->save();
            Db::commit();
            mb_OutMessage(ErrCode_Normal, '保存成功');
        } catch (\Exception $e) {
            Db::rollback();
            mb_OutMessage(ErrCode_Normal, $e->getMessage());
        }
    }

    /**
     * 重設個人頭像
     */
    public function mb_ResetIcon()
    {
        $Token = Request::has('Token') ? addslashes(Request::param('Token')) : '';
        $Icon = Request::has('Icon') ? addslashes(Request::param('Icon')) : '';

        $User = new User();
        $UserData = $User->mb_Get("MobileToken='$Token' AND IsDeleted='0'");
        if ($UserData == null || $UserData['Level'] != Level_CRMUser) mb_OutMessage(ErrCode_Distance, ErrMsg_Distance);

        if (!$Icon) mb_OutMessage(ErrCode_Toast, '参数有误!');

        Db::startTrans();
        try {
            $UserData->Icon = $Icon;
            $UserData->save();
            Db::commit();
            mb_OutMessage(ErrCode_Normal, '保存成功');
        } catch (\Exception $e) {
            Db::rollback();
            mb_OutMessage(ErrCode_Normal, $e->getMessage());
        }
    }

    /**
     * 重設個人密碼
     */
    public function mb_ResetPassword()
    {
        $Token = Request::has('Token') ? addslashes(Request::param('Token')) : '';
        $OldPass = Request::has('OldPass') ? addslashes(Request::param('OldPass')) : '';
        $NewPass = Request::has('NewPass') ? addslashes(Request::param('NewPass')) : '';

        $UserData = $this->mb_CheckLogin($Token);
        if ($OldPass != $UserData->BasePass) mb_OutMessage(ErrCode_Toast, '旧密码不正确');

        Db::startTrans();
        try {
            $UserData->EncPass = md5($NewPass);
            $UserData->BasePass = $NewPass;
            $UserData->save();
            Db::commit();
            mb_OutMessage(ErrCode_Normal, '保存成功');
        } catch (\Exception $e) {
            Db::rollback();
            mb_OutMessage(ErrCode_Normal, $e->getMessage());
        }
    }

    /**
     * 提交錯誤報告
     */
    public function mb_SubmitErrorReport()
    {
        $Token = Request::has('Token') ? addslashes(Request::param('Token')) : '';
        $Email = Request::has('Email') ? addslashes(Request::param('Email')) : '';
        $Content = Request::has('Content') ? addslashes(Request::param('Content')) : '';
        $ImageUrls = Request::has('ImageUrls') ? Request::param('ImageUrls') : '[]';

        if (!$Content && !$Email && $ImageUrls=='[]') mb_OutMessage(ErrCode_Toast, '请输入相关报告内容');
        $UserData = $this->mb_CheckLogin($Token);

        Db::startTrans();
        try {
            Db::table('error_report')->insert(array(
                'UserID' => $UserData->ID,
                'Email' => $Email,
                'Content' => $Content,
                'ImageUrls' => $ImageUrls
            ));
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            mb_OutMessage(ErrCode_Normal, $e->getMessage());
        }
        if ($Email != '') {
            //这里发送回感谢提交电邮
        }

        mb_OutMessage(ErrCode_Normal, '感谢您的提交，我们收到您的错误报告后将会第一时间与您联系');
    }

    private function mb_CheckLogin($Token)
    {
        $User = new User();
        $UserData = $User->mb_Get("MobileToken='$Token' AND IsDeleted='0'");
        if ($UserData == null || $UserData['Level'] != Level_CRMUser) mb_OutMessage(ErrCode_Distance, ErrMsg_Distance);
        return $UserData;
    }
}